package com.atguigu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.commont.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/24 14:27
 */
public class DwmUvApp extends BaseAppV1 {
    public static void main(String[] args) {
        /*
        dwd_page  dwd_start dwd_display
        
        启动日志:
            计算uv, 结果会偏小
            
            app访问
                才有启动日志
            
            网页访问
                没有启动日志
        页面日志:
            过滤出来当前设备id, 他的第一条访问记录
         */
        new DwmUvApp().init(3001, 1, "DwmUvApp", "DwmUvApp", Constant.TOPIC_DWD_PAGE);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((log, ts) -> log.getLong("ts"))
            )
            .keyBy(log -> log.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private SimpleDateFormat sdf;
                private ValueState<Long> firstVisitState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("fistVisitState", Long.class));
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                    
                }
                
                @Override
                public void process(String s,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    
                    String yesterday = sdf.format(firstVisitState.value() == null ? 0L : firstVisitState.value());
                    String today = sdf.format(ctx.window().getStart());
                    
                    if (!today.equals(yesterday)) {
                        firstVisitState.clear();
                    }
                    
                    if (firstVisitState.value() == null) {
                        // 第一个窗口来了, 找到时间戳最小的那个记录
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        //                        Collections.min(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        JSONObject first = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        
                        out.collect(first);
                        
                        firstVisitState.update(first.getLong("ts"));
                        
                    }
                    
                }
            })
            .map(JSON::toString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_UV));
        
    }
}
